<template>
  <div class="chess-game">
    <div class="game-container">
      <div class="left-panel">
        <div class="ai-analysis-container" v-if="isAIEnabled">
          <h3 class="panel-title">AI 分析</h3>
          <div class="panel-content">
            <AIEvaluation />
          </div>
        </div>
      </div>

      <div class="center-panel">
        <div class="game-info">
          <div class="timer black">{{ formatTime(gameTime.black) }}</div>
        </div>
        
        <div class="chess-board">
          <div v-for="row in 8" :key="row" class="board-row">
            <div 
              v-for="col in 8" 
              :key="col" 
              class="board-cell"
              :class="[
                getCellColor(row, col),
                { 
                  'highlighted': isHighlighted(row-1, col-1),
                  'valid-move': isValidMove(row-1, col-1),
                  'last-move-from': isLastMoveFrom(row-1, col-1),
                  'last-move-to': isLastMoveTo(row-1, col-1)
                }
              ]"
              @click="handleCellClick(row-1, col-1)"
            >
              <template v-if="getPiece(row-1, col-1)">
                <ChessPiece
                  :piece="getPiece(row-1, col-1)!"
                  :can-move="isValidMove(row-1, col-1)"
                  @piece-click="handlePieceClick(row-1, col-1)"
                />
              </template>
            </div>
          </div>
        </div>

        <div class="game-info">
          <div class="timer white">{{ formatTime(gameTime.white) }}</div>
        </div>
      </div>

      <div class="right-panel">
        <div class="move-history-container">
          <h3 class="panel-title">棋谱记录</h3>
          <div class="panel-content">
            <div class="move-history">
              <div v-for="(move, index) in moveHistory" :key="index" 
                   class="move-entry"
                   :class="{ 
                     'white-move': index % 2 === 0,
                     'black-move': index % 2 === 1 
                   }">
                <span class="move-number">{{ Math.floor(index/2) + 1 }}.</span>
                <span class="move-notation" :class="{ 'black-notation': index % 2 === 1 }">{{ move }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="game-controls">
      <div class="control-group">
        <button class="control-btn primary" @click="saveGame">保存游戏</button>
        <button class="control-btn" @click="pauseTimer">暂停</button>
        <button class="control-btn" @click="startTimer">继续</button>
        <button class="control-btn" @click="handleUndo" :disabled="!canUndo">悔棋</button>
      </div>
      
      <div class="ai-controls">
        <select v-model="aiDifficulty" class="difficulty-select">
          <option value="easy">简单</option>
          <option value="medium">中等</option>
          <option value="hard">困难</option>
        </select>
        <button class="control-btn" 
                :class="{ 'ai-active': isAIEnabled }"
                @click="toggleAI">
          {{ isAIEnabled ? '关闭AI' : '开启AI' }}
        </button>
      </div>

      <div class="control-group">
        <button class="control-btn" @click="showStats = true">统计</button>
        <button class="control-btn" @click="showReplay = true">回放</button>
      </div>
    </div>

    <PawnPromotionDialog
      :show="showPromotionDialog"
      :color="promotionColor"
      @select="handlePromotion"
    />

    <StatsDialog
      :show="showStats"
      @close="showStats = false"
    />

    <ReplayDialog
      :show="showReplay"
      :moves="moveHistory"
      :initial-board="initialBoard"
      @close="showReplay = false"
    />

    <div class="chess-rules">
      <h3>国际象棋规则说明：</h3>
      <div class="rules-content">
        <div class="rule-section">
          <h4>基本规则：</h4>
          <ul>
            <li>白方先行，双方轮流移动一枚棋子</li>
            <li>棋子不能移动到被己方棋子占据的格子</li>
            <li>除马以外的棋子不能跨越其他棋子移动</li>
          </ul>
        </div>
        <div class="rule-section">
          <h4>特殊规则：</h4>
          <ul>
            <li>兵第一次可以走一格或两格，之后只能前进一格</li>
            <li>兵到达对方底线时可以升变为后、车、马或象</li>
            <li>王车易位：王和车的特殊移动组合，用于保护王</li>
            <li>过路兵：吃掉刚走两格的对方兵</li>
          </ul>
        </div>
        <div class="rule-section">
          <h4>胜负判定：</h4>
          <ul>
            <li>将死：对方王被将军且无法脱离，游戏结束</li>
            <li>和棋：双方同意和棋或出现无法将死的局面</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, computed, watch } from 'vue'
import { useGameState } from '../composables/useGameState'
import { useChessGame } from '../composables'
import type { Position } from '../types/chess'
import ChessPiece from './ChessPiece.vue'
import PawnPromotionDialog from './PawnPromotionDialog.vue'
import { useChessSound } from '../composables/useChessSound'
import { useChessAI } from '../composables/useChessAI'
import StatsDialog from './StatsDialog.vue'
import { useChessStats } from '../composables/useChessStats'
import ReplayDialog from './ReplayDialog.vue'
import { useAdaptiveAI } from '../composables/useAdaptiveAI'
import AIEvaluation from './AIEvaluation.vue'

// 初始化游戏状态
const gameState = useGameState()
const {
  gameTime,
  moveHistory,
  capturedPieces,
  startTimer,
  pauseTimer,
  saveGame,
  addMove,
  addCapture,
  undoMove,
  moveStack
} = gameState
// 初始化棋局逻辑
const chessGame = useChessGame({
  gameTime: gameTime.value,
  moveHistory: moveHistory.value,
  capturedPieces: capturedPieces.value,
  moveStack: moveStack.value,
  addMove,
  addCapture,
  undoMove
}) 
const {
  board,
  selectedPiece,
  getPiece,
  isValidMove,
  selectPiece,
  movePiece,
  isCheck,
  isCheckmate,
  calculateValidMoves,
  currentPlayer,
  lastMove
} = chessGame

const showPromotionDialog = ref(false)
const promotionColor = ref<'white' | 'black'>('white')
const promotionPosition = ref<{ row: number, col: number } | null>(null)

const { initAudio, playMove, playCapture, playCheck } = useChessSound()
const canUndo = computed(() => moveStack.value.length > 0)

// 初始化 AI
const { findBestMove, setDifficulty } = useChessAI()
const isAIEnabled = ref(false)
const aiDifficulty = ref<'easy' | 'medium' | 'hard'>('medium')

// 监听 AI 难度变化
watch(aiDifficulty, (newValue) => {
  setDifficulty(newValue)
})

// 切换 AI
const toggleAI = () => {
  isAIEnabled.value = !isAIEnabled.value
}

// 格式化时间显示
const formatTime = (seconds: number) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 获取棋盘格子颜色
const getCellColor = (row: number, col: number) => {
  return (row + col) % 2 === 0 ? 'white-cell' : 'black-cell'
}

// 检查是否高亮显示
const isHighlighted = (row: number, col: number) => {
  return selectedPiece.value && 
    selectedPiece.value.row === row && 
    selectedPiece.value.col === col
}

// 处理子点击
const handlePieceClick = (row: number, col: number) => {
  selectPiece(row, col)
}

// 修改处理移动的逻辑
const handleCellClick = async (row: number, col: number) => {
  // 如果是 AI 的回合，允许移动
  if (isAIEnabled.value && currentPlayer.value === 'black') {
    return
  }

  // 如果点击的是己方棋子，则选中它
  const piece = board.value[row][col]
  if (piece && piece.includes(currentPlayer.value)) {
    selectPiece(row, col)
    return
  }

  // 如果已经选中了棋子，且目标位置是有效移动，则尝试移动
  if (selectedPiece.value && isValidMove(row, col)) {
    const result = movePiece(row, col)
    
    if (result) {
      // 播放音效
      if (board.value[row][col]) {
        playCapture()
      } else {
        playMove()
      }

      if (isCheck.value) {
        playCheck()
      }

      // 处理兵的升变
      if (result.needsPromotion) {
        showPromotionDialog.value = true
        promotionColor.value = result.color
        promotionPosition.value = { row, col }
        return
      }

      // AI 移动
      if (isAIEnabled.value && currentPlayer.value === 'black') {
        await new Promise(resolve => setTimeout(resolve, 500))
        
        let allValidMoves: Position[] = []
        
        // 收集所有黑方棋子的有效移动
        for (let r = 0; r < 8; r++) {
          for (let c = 0; c < 8; c++) {
            const piece = board.value[r][c]
            if (piece && piece.includes('black')) {
              selectPiece(r, c)
              const moves = calculateValidMoves(r, c)
              moves.forEach((move: Position) => {
                allValidMoves.push({
                  row: move.row,
                  col: move.col,
                  from: { row: r, col: c }
                })
              })
            }
          }
        }

        const aiMove = findBestMove(board.value, allValidMoves, 'black', calculateValidMoves)
        
        if (aiMove && 'from' in aiMove && aiMove.from) {
          selectPiece(aiMove.from.row, aiMove.from.col)
          const aiResult = movePiece(aiMove.row, aiMove.col)
          if (aiResult) {
            if (board.value[aiMove.row][aiMove.col]) {
              playCapture()
            } else {
              playMove()
            }
            if (isCheck.value) {
              playCheck()
            }
          }
        }
      }
    }
  }
}

// 生命周期钩子
onMounted(() => {
  startTimer()
  initAudio()
})

onUnmounted(() => {
  pauseTimer()
})

const handlePromotion = (piece: string) => {
  if (promotionPosition.value) {
    const { row, col } = promotionPosition.value
    board.value[row][col] = `${promotionColor.value}-${piece}`
    showPromotionDialog.value = false
    promotionPosition.value = null
  }
}

// 处理悔棋
const handleUndo = () => {
  if (undoMove()) {
    playMove()
  }
}

const showStats = ref(false)
const { updateStats } = useChessStats()

// 在游戏结束时更新统计
watch(isCheckmate, (newVal) => {
  if (newVal) {
    const winner = currentPlayer.value === 'white' ? 'black' : 'white'
    updateStats({
      winner,
      moves: moveHistory.value.length,
      playTime: 600 - gameTime.value[winner]
    })
    
    // 更新 AI 性能
    if (selectedPiece.value) {
      updatePerformance(
        winner === 'white' ? 'win' : 'loss',
        evaluateMoveQuality(
          { 
            from: selectedPiece.value, 
            to: { row: 0, col: 0 } 
          },
          { row: 0, col: 0 },
          board.value
        )
      )
    }
  }
})

const showReplay = ref(false)

const {
  currentDifficulty,
  evaluateMoveQuality,
  updatePerformance
} = useAdaptiveAI()

// 监听AI难度变化
watch(currentDifficulty, (newDifficulty) => {
  setDifficulty(newDifficulty)
})

const initialBoard = [
  ['black-rook', 'black-knight', 'black-bishop', 'black-queen', 'black-king', 'black-bishop', 'black-knight', 'black-rook'],
  ['black-pawn', 'black-pawn', 'black-pawn', 'black-pawn', 'black-pawn', 'black-pawn', 'black-pawn', 'black-pawn'],
  Array(8).fill(null),
  Array(8).fill(null),
  Array(8).fill(null),
  Array(8).fill(null),
  ['white-pawn', 'white-pawn', 'white-pawn', 'white-pawn', 'white-pawn', 'white-pawn', 'white-pawn', 'white-pawn'],
  ['white-rook', 'white-knight', 'white-bishop', 'white-queen', 'white-king', 'white-bishop', 'white-knight', 'white-rook']
] as (string | null)[][]

// 在 script 部分添加类型定义
interface ChessPieceProps {
  piece: string
  canMove?: boolean
  mini?: boolean
}

// 添加新的检查函数
const isLastMoveFrom = computed(() => (row: number, col: number): boolean => {
  const move = chessGame.lastMove.value
  return move?.from?.row === row && move?.from?.col === col || false
})

const isLastMoveTo = computed(() => (row: number, col: number): boolean => {
  const move = chessGame.lastMove.value
  return move?.to?.row === row && move?.to?.col === col || false
})

const isLastMovedPiece = computed(() => (row: number, col: number): boolean => {
  const move = chessGame.lastMove.value
  return move?.to?.row === row && move?.to?.col === col
})
</script>

<style scoped>
/* 基础布局 */
.chess-game {
  padding: 20px;
}

.game-container {
  display: grid;
  grid-template-columns: 250px 1fr 250px;
  gap: 20px;
  align-items: flex-start;
}

/* 面板通用样式 */
.ai-analysis-container,
.move-history-container {
  background: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border: 1px solid #e2e8f0;
  height: 500px;
  display: flex;
  flex-direction: column;
}

.panel-title {
  background: #b58863;
  color: #fff;
  margin: 0;
  padding: 12px 16px;
  font-size: 1.1em;
  border-bottom: 1px solid #a47853;
  text-align: center;
  font-weight: 600;
}

.panel-content {
  flex: 1;
  overflow: hidden;
  padding: 16px;
  background: #fff;
}

/* 中央面板样式 */
.center-panel {
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 计时器样式 */
.game-info {
  margin: 10px 0;
  text-align: center;
}

.timer {
  font-size: 24px;
  font-weight: bold;
  color: #2c3e50;
  padding: 8px 16px;
  border-radius: 4px;
  background: #f8fafc;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.timer.black {
  margin-bottom: 10px;
}

.timer.white {
  margin-top: 10px;
}

/* 棋盘样式 */
.chess-board {
  width: 400px;
  height: 400px;
  border: 2px solid #333;
}

.board-row {
  display: flex;
  height: 12.5%;
}

.board-cell {
  width: 12.5%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.white-cell {
  background-color: #fff;
}

.black-cell {
  background-color: #b58863;
}

.highlighted {
  background-color: rgba(255, 255, 0, 0.3) !important;
}

.valid-move::after {
  content: '';
  position: absolute;
  width: 12px;
  height: 12px;
  background-color: rgba(76, 175, 80, 0.8);
  border-radius: 50%;
  pointer-events: none;
  z-index: 1;
}

/* 棋谱记录样式 */
.move-history {
  height: 100%;
  overflow-y: auto;
  padding: 0 12px;
}

.move-entry {
  display: flex;
  padding: 8px 12px;
  margin: 3px 0;
  font-family: 'Consolas', monospace;
  align-items: center;
  transition: background-color 0.2s;
}

.white-move {
  background-color: #ffffff;
  border-left: 4px solid #2c3e50;
}

.white-move .move-number {
  color: #1a202c;
  font-weight: 700;
}

.white-move .move-notation {
  color: #000000;
  font-weight: 600;
  font-size: 1.1em;
}

.black-move {
  color: #fff;
  background-color: #4b5563;
  padding-left: 24px;
}

.black-move .move-number,
.black-move .move-notation {
  font-weight: 600;
  font-size: 1.1em;
}

/* 控制按钮样式 */
.game-controls {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
  padding: 15px;
  background: #f8fafc;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.control-group {
  display: flex;
  gap: 10px;
}

.control-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  background: #e2e8f0;
  color: #475569;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.control-btn:hover {
  background: #cbd5e1;
}

.control-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.control-btn.primary {
  background: #2c3e50;
  color: white;
}

.control-btn.primary:hover {
  background: #1e2a37;
}

.control-btn.ai-active {
  background: #4CAF50;
  color: white;
}

/* AI 控制样式 */
.ai-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.difficulty-select {
  padding: 8px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  background: white;
  color: #475569;
  font-size: 14px;
  cursor: pointer;
}

.difficulty-select:focus {
  outline: none;
  border-color: #2c3e50;
}

/* 规则说明样式 */
.chess-rules {
  grid-column: 1 / -1;
  margin-top: 20px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.chess-rules h3 {
  color: #333;
  margin-bottom: 15px;
  text-align: center;
}

.rules-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.rule-section {
  padding: 10px;
}

.rule-section h4 {
  color: #4CAF50;
  margin-bottom: 10px;
}

.rule-section ul {
  list-style-type: none;
  padding-left: 0;
}

.rule-section li {
  margin-bottom: 8px;
  padding-left: 20px;
  position: relative;
}

.rule-section li::before {
  content: "•";
  color: #4CAF50;
  position: absolute;
  left: 0;
  font-weight: bold;
}

/* 滚动条样式 */
.move-history::-webkit-scrollbar {
  width: 4px;
}

.move-history::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.move-history::-webkit-scrollbar-thumb {
  background: #cbd5e1;
}

.move-history::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

/* 修改最后移动的样式，让它更加明显 */
.last-move-from {
  position: relative;
}

.last-move-from::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 215, 0, 0.3);  /* 金色背景 */
  z-index: 1;
}

.last-move-to {
  position: relative;
}

.last-move-to::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 215, 0, 0.5);  /* 更深的金色背景 */
  border: 3px solid #FFD700;  /* 加粗的金色边框 */
  box-shadow: 0 0 10px #FFD700;  /* 添加发光效果 */
  animation: pulse 1.5s infinite;  /* 添加脉冲动画 */
  z-index: 1;
}

/* 添加脉冲动画 */
@keyframes pulse {
  0% {
    box-shadow: 0 0 5px #FFD700;
    border-color: #FFD700;
  }
  50% {
    box-shadow: 0 0 20px #FFD700;
    border-color: #FFA500;
  }
  100% {
    box-shadow: 0 0 5px #FFD700;
    border-color: #FFD700;
  }
}

/* 确保样式优先级 */
.board-cell {
  position: relative;
}

.valid-move::after {
  z-index: 3;
}
</style> 